package myArrayList;

import java.util.Arrays;

public class MyArrayList implements ILIst{
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_FALSE=10;
    public MyArrayList(){
        this.elem=new int[DEFAULT_FALSE];
    }
    public MyArrayList(int customized){
        this.elem=new int[customized];
    }
    private boolean isFull(){
        return usedSize==elem.length;
    }
    private void Expansion(){
        if(isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
    }
    @Override
    public void add(int data) {
        Expansion();
        elem[usedSize]=data;
        this.usedSize++;
    }
    public void isLegal(int pos)throws PosLegality{
        if(pos<0||pos>usedSize){
            System.out.println("不合法");
            throw new PosLegality("元素下标异常"+pos);
        }
    }
    public void isLegalGetAndSet(int pos)throws PosLegislation{
        if(pos<0||pos>usedSize){
            System.out.println("不合法");
            throw new PosLegislation("获取指定元素下标异常");
        }
    }
    @Override
    public void add(int index, int data) throws PosLegality{
        //先判断pos的合法性（大于0且小于usedSize）
        try{
            isLegal(index);
        }catch (PosLegality p){
            p.printStackTrace();
        }
        Expansion();
        for (int i = usedSize-1; i >=index; i--) {
            elem[i+1]=elem[i];
        }
        elem[index]=data;
        this.usedSize++;
    }
    private boolean isEmpty(){
        return usedSize==0;
    }
    @Override
    public boolean contains(int toFind){
        if(isEmpty()) {
            return false;
        }
        for (int i = 0; i < usedSize; i++) {
            //如果是查找引用数据类型 一定记住 重写方法
            if(elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind){
        if(isEmpty()){
            return -1;
        }
        for (int i = 0; i < usedSize; i++) {
            if(elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) throws PosLegislation{
        isLegalGetAndSet(pos);
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        isLegalGetAndSet(pos);
        elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int index=indexOf(toRemove);
        if(index==-1){
            System.out.println("找不到");
            return;
        }
        for (int i = index; i < usedSize-1; i++) {
            elem[i]=elem[i+1];
        }
        usedSize--;
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public void clear() {
        this.usedSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

}
